package com.winning.common.data.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.framework.helper.PageHelper;
import com.framework.helper.ServerSQLExecutorUtils;
import com.framework.server.db.bean.PageBean;
import com.framework.server.db.bean.PageQueryBean;
import com.framework.util.date.DateConvert;
import com.winning.common.Constans;
import com.winning.common.data.dao.AppBaseDao;
import com.winning.common.data.dao.inter.PlatBasicDataDaoInter;

@Repository(value = "com.winning.lang.data.dao.impl.PlatBasicDataDao")
public class PlatBasicDataDao extends AppBaseDao implements PlatBasicDataDaoInter {
    private static Logger LOGGER = Logger.getLogger("pbsLoger");

    /**
     * 获取患者信息数据接口 <br/>
     * 方法名称: getPatientPersionInfoDataService
     *
     * @param
     * @return List<JSONObject>  返回类型说明<br/>
     * @throws <br/>
     * @author liuwensheng@winning.com.cn<br/>
     * 创建时间：2016-12-9/上午10:39:48<br/>
     */
    @Override
    public List<Map<String, Object>> getPatientPersionInfoDataService() {
        String sql = "SELECT TOP 100 * FROM DA_GR_JBXX";

        List<Map<String, Object>> result = executeQueryReturnMapList(sql, null);

        return result;
    }


    /**
     * 根据提供的SQL获取平台基础数据源 <br/>
     * 方法名称: getPlatBasicDataBySQLService
     *
     * @param
     * @return List<JSONObject>  返回类型说明<br/>
     * @throws <br/>
     * @author liuwensheng@winning.com.cn<br/>
     * 创建时间：2016-12-9/上午10:39:48<br/>
     */
    @Override
    public List<Map<String, Object>> getPlatBasicDataBySQLService(String sql) {
        List<Map<String, Object>> result = executeQueryReturnMapList(sql, null);

        return result;
    }

    /**
     * 根据提供的SQL获取平台基础数据源，可指定数据库 <br/>
     * 方法名称: getPlatBasicDataBySQLService
     *
     * @param sql
     * @param dataSourseID 数据源ID
     * @return List<HashMap                                                                                                                               <                                                                                                                               String                                                                                                                               ,                                                                                                                                                                                                                                                               Object>>  返回类型说明<br/>
     * @throws <br/>
     * @author liuwensheng@winning.com.cn<br/>
     * 创建时间：2016-12-9/上午10:39:48<br/>
     */
    @Override
    public List<HashMap<String, Object>> getPlatBasicDataByDataSourseIDService(String sql, String dataSourseID) {

        List<HashMap<String, Object>> result = executeQueryReturnMapListByDataSource(sql, null, dataSourseID);

        return result;
    }

    /**
     * 由于SYS_SJSC_TABLE中tableName字段存在主键唯一约束性，需要判断是做新增还是修改操作
     *
     */
    @Override
    public void insertBusnisseLastTime(String type, String serviceName, String mapKey, String lastTimeValueFromLocal, String dataSourseID) {


        LOGGER.info("--> 进入 insertBusnisseLastTime ");

        //判断是否有OR
        if (dataSourseID.indexOf(Constans.DATA_SOURCE_ORACLE_TAG) > -1) {
            //oracler日期不支持毫秒
            lastTimeValueFromLocal = lastTimeValueFromLocal.substring(0, 19);
        }

        try {
            String excSQL = "";


            String sql = "select *  from SYS_SJSC_TABLE where TABLE_NAME = '" + mapKey + "'";
            LOGGER.info("--> 开始更新增量更新时间" + sql);
            List<HashMap<String, Object>> resultMap = ServerSQLExecutorUtils.executeQuery(sql, dataSourseID);
            int count = resultMap.size();
//			int count = (Integer) ServerSQLExecutorUtils.executeQuery(sql, new Object[] { mapKey }, ServerSQLExecutorUtils.TOTALCOUNT);

            if (count > 0) {
                if (dataSourseID.indexOf(Constans.DATA_SOURCE_ORACLE_TAG) > -1) {
                    //修改SQL
                    excSQL = "UPDATE SYS_SJSC_TABLE SET TABLE_TIME = to_date('" + lastTimeValueFromLocal + "','YYYY_MM_DD HH24:MI:SS') WHERE TABLE_NAME = '" + mapKey + "'";
                } else {

                    //修改SQL
                    excSQL = "UPDATE SYS_SJSC_TABLE SET TABLE_TIME = '" + lastTimeValueFromLocal + "' WHERE TABLE_NAME = '" + mapKey + "'";
                }

            } else {
                /**
                 //张家港表结构发生改变
                 if("zjg".equals(type))
                 {
                 String nowDateValue = DateConvert.getNowYYYY_MM_DD_HH_MM_DD();
                 //新增SQL ,SCKSSJ值无意义
                 excSQL = "INSERT INTO SYS_SJSC_TABLE (SCKSSJ, TABLE_NAME, TABLE_TIME) VALUES ('" + nowDateValue  + "', '" + mapKey + "', '" + lastTimeValueFromLocal + "')";
                 }
                 else
                 {
                 //新增SQL
                 excSQL = "INSERT INTO SYS_SJSC_TABLE VALUES ('" + mapKey + "', to_date('" + lastTimeValueFromLocal + "','YYYY_MM_DD HH24:MI:SS'))";
                 }
                 **/

                if (dataSourseID.indexOf(Constans.DATA_SOURCE_ORACLE_TAG) > -1) {
                    //新增SQL
                    excSQL = "INSERT INTO SYS_SJSC_TABLE VALUES ('" + mapKey + "', to_date('" + lastTimeValueFromLocal + "','YYYY_MM_DD HH24:MI:SS'))";
                } else {

                    //新增SQL
                    excSQL = "INSERT INTO SYS_SJSC_TABLE VALUES ('" + mapKey + "', '" + lastTimeValueFromLocal + "')";
                }


            }

            LOGGER.info("--> [" + serviceName + "], Insert into SYS_SJSC_TABLE SQL:[" + excSQL + "]");

            ServerSQLExecutorUtils.execute(excSQL, null, dataSourseID);


        } catch (SQLException e) {
            //打印异常堆栈信息
            LOGGER.error(e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public HashMap<String, String> getTableIncreaseTimeMapFromDB(String dataSourseID) {
        HashMap<String, String> tableTimeMap = new HashMap<String, String>();

        LOGGER.info("-->获取增量更新时间数据源   ： [" + dataSourseID + "]");

        String basicSQL = "SELECT TABLE_NAME, TABLE_TIME FROM SYS_SJSC_TABLE";

        List<HashMap<String, Object>> rs = null;

        try {
            rs = ServerSQLExecutorUtils.executeQuery(basicSQL, dataSourseID);

            if (rs == null) {
                return tableTimeMap;
            }

//			rs.beforeFirst();
//
//			while(rs.next())
//			{
//				//时间格式统一为YYYY-MM-DD HH:MM:SS
//				String tableName = rs.getObject("TABLE_NAME") == null ? "" : rs.getObject("TABLE_NAME").toString();
//				String tableTime = rs.getObject("TABLE_TIME") == null ? "" : rs.getObject("TABLE_TIME").toString();
//
//				if(!"".equals(tableName) && !"".equals(tableTime))
//				{
//					//tableName的格式为：serviceID%tablename
//					tableTimeMap.put(tableName.toUpperCase(), tableTime);
//				}
//			}


            for (HashMap<String, Object> map : rs) {
                LOGGER.info("-->增量更新时间   ： [" + map.toString() + "]");
                String tableName = map.get("TABLE_NAME").toString();
                String tableTime = map.get("TABLE_TIME").toString();
                //判断是否有OR
                if (dataSourseID.indexOf(Constans.DATA_SOURCE_ORACLE_TAG) > -1) {
                    // oracle date日期类型不支持毫秒
                    tableTime = tableTime.substring(0, 19);
                }


                if (!"".equals(tableName) && !"".equals(tableTime)) {
                    //tableName的格式为：serviceID%tablename
                    tableTimeMap.put(tableName.toUpperCase(), tableTime);
                }
            }


        } catch (Exception e) {
            //打印异常堆栈信息
            LOGGER.error(e, e.fillInStackTrace());

            e.printStackTrace();
        }


        return tableTimeMap;
    }

    /**
     * @param sql
     * @param columnName
     * @param dataSourseID
     * @return int
     * @throws
     * @Title: queryTotalDataCount
     * @Description: 统计接口
     */
    @Override
    public int queryTotalDataCount(String sql, String columnName, String dataSourseID) {
        int result = -1;

        try {
            List<HashMap<String, Object>> resultMap = ServerSQLExecutorUtils.executeQuery(sql, dataSourseID);


            if (resultMap != null) {

//				LOGGER.info("resultMap size = " + resultMap.size());
//				LOGGER.info("HashMap = " + resultMap.get(0).toString());

                Object objValue = resultMap.get(0).get(columnName);

                result = Integer.parseInt(objValue.toString());
                //result = resultMap.size();
            }

        } catch (Exception e) {
            //打印异常堆栈信息
            LOGGER.error(e.toString());

            e.printStackTrace();
        }

        return result;
    }

    /**
     * 分页查询数据
     *
     * @param pageBean
     * @param basicSQL
     * @param orderStr
     * @return
     * @throws SQLException
     */
    public PageQueryBean getParamByPageQuery(PageBean pageBean, String basicSQL, String orderStr, String dataSourseID) throws SQLException {
        //按照分页从数据库中提取数据
        PageQueryBean pageQueryBean = null;
        try {

            //判断是否有OR
            if (dataSourseID.indexOf(Constans.DATA_SOURCE_ORACLE_TAG) > -1) {
                pageQueryBean = PageHelper.pageQuery(basicSQL, orderStr, pageBean, PageHelper.OraclePaging, dataSourseID, PageHelper.LowerXMLResultHandler);

            } else {
                pageQueryBean = PageHelper.pageQuery(basicSQL, orderStr, pageBean, PageHelper.SQLPaging, dataSourseID, PageHelper.LowerXMLResultHandler);
            }
        } catch (SQLException e) {
            //打印异常堆栈信息
            LOGGER.error(e, e.fillInStackTrace());

            e.printStackTrace();

            return null;
        }

        return pageQueryBean;
    }


    /**
     * 增加基本信息注册信息返回结果
     * 方法名称: insertPersionRegisterResult
     *
     * @param
     * @return void  返回类型说明<br/>
     * @throws <br/>
     * @author zq@winning.com.cn<br/>
     * 创建时间：Dec 22, 2016/3:43:27 PM<br/>
     */
    @Override
    public int insertJBXXRegisterResult(String sql, Object[] params, String dataSourseID) {
        try {

            //打印异常堆栈信息
            LOGGER.info("--> 执行 个人信息注册结果插入语句  = " + sql);

            ServerSQLExecutorUtils.execute(sql, params, dataSourseID);

            return 0;
        } catch (SQLException e) {
            //打印异常堆栈信息
            LOGGER.error(e);

            e.printStackTrace();
            return -1;
        }

    }


    /**
     * 执行sql语句获取结果
     * 方法名称: executeSQLByDataSourseID
     *
     * @param
     * @return List<HashMap                                                                                                                               <                                                                                                                               String                                                                                                                               ,                                                                                                                               Object>>  返回类型说明<br/>
     * @throws <br/>
     * @author zq@winning.com.cn<br/>
     * 创建时间：2017-1-13/上午9:02:46<br/>
     */
    @Override
    public List<HashMap<String, Object>> executeSQLByDataSourseID(String sql, Object[] params, String dataSourseID) {
        try {
            List<HashMap<String, Object>> result = executeQueryReturnMapListByDataSource(sql, params, dataSourseID);

            return result;

        } catch (Exception e) {
            e.printStackTrace();

            LOGGER.error(e.getMessage());
            return null;
        }
    }


    /**
     * 执行SQL语句，获取JSONObject对象
     * 方法名称: executSQLForJSONObject
     *
     * @param
     * @return JSONObject  返回类型说明<br/>
     * @throws <br/>
     * @author lenovo@winning.com.cn<br/>
     * 创建时间：2017-2-7/上午10:55:32<br/>
     */
    @Override
    public JSONObject executSQLForJSONObject(String sql, Object[] params, String dataSourseID) {

        try {
            JSONObject result = executeQueryReturnJSONByDataSource(sql, params, dataSourseID);

            return result;

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            return null;
        }
    }


    /**
     * 执行SQL语句获取json数组对象
     * 方法名称: executeSQLForJSONArrayList
     *
     * @param
     * @return List<JSONObject>  返回类型说明<br/>
     * @throws <br/>
     * @author lenovo@winning.com.cn<br/>
     * 创建时间：2017-2-7/下午1:21:26<br/>
     */
    @Override
    public List<JSONObject> executeSQLForJSONArrayList(String sql, Object[] params, String dataSourseID) {

        try {
            List<JSONObject> result = executeQueryReturnJSONListByDataSource(sql, params, dataSourseID);

            return result;

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e);
            return null;
        }
    }


}
